﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DimensionData.Data2
{
    public class DData
    {
        public DTable Table { get; set; }

        public List<DDataNode> Nodes { get; set; }

        public DData()
        {
            Nodes = new List<DDataNode>();
        }

        public DTree ConvertToTree()
        {
            DTree tree = new DTree();

            for (int index = 0; index < Nodes.Count; index++)
            {
                ConvertNode(tree, Nodes[index]);
            }
            return tree;
        }

        private void ConvertNode(DTree tree, DDataNode dataNode)
        {
            DTreeNode treeNode = new DTreeNode();
            treeNode.Tree = tree;
            treeNode.Level = dataNode.Level;
            treeNode.Code = dataNode.Code;
            treeNode.Name = dataNode.Name;
            treeNode.Formula = dataNode.Formula;

            for (int index = 0; index < dataNode.Nodes.Count; index++)
            {
                DDataNode subDataNode = dataNode.Nodes[index];
                ConvertNode(treeNode, subDataNode);
            }
            tree.Nodes.Add(treeNode);
        }

        private void ConvertNode(DTreeNode node, DDataNode dataNode)
        {
            DTreeNode treeNode = new DTreeNode();
            treeNode.Tree = node.Tree;
            treeNode.Level = dataNode.Level;
            treeNode.Code = dataNode.Code;
            treeNode.Name = dataNode.Name;
            treeNode.Formula = dataNode.Formula;


            for (int index = 0; index < dataNode.Nodes.Count; index++)
            {
                DDataNode subDataNode = dataNode.Nodes[index];
                ConvertNode(treeNode, subDataNode);
            }
            node.Nodes.Add(treeNode);
        }

        public List<DRow> Complanate2()
        {
            List<DRow> rows = new List<DRow>();

            Stack<DDataNode> stack = new Stack<DDataNode>();
            for (int index = Nodes.Count - 1; index >= 0; index--)
            {
                stack.Push(Nodes[index]);
            }

            while (stack.Count > 0)
            {
                DDataNode node = stack.Pop();

                DRow row = new DRow();
                row.RowIndex = rows.Count;
                rows.Add(row);

                row.Items = new DItem[1];
                row.Items[0] = new DItem();

                row.Items[0].Code = node.Code;
                row.Items[0].Name = node.Name;
                row.Items[0].Level = node.Level;
                row.Items[0].Formula = node.Formula;

                for (int index = node.Nodes.Count - 1; index >= 0; index--)
                {
                    stack.Push(node.Nodes[index]);
                }
            }

            return rows;
        }
    }
}
